package com.oplink.webems.modules.alarm.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceUnit;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Component;

import com.oplink.webems.common.persistence.BaseDao;
import com.oplink.webems.common.persistence.BaseDaoImpl;
import com.oplink.webems.modules.alarm.entity.AlarmCurrent;
import com.oplink.webems.modules.alarm.entity.TrapOid;

/**
 * Current Alarm Dao
 * @author yizhang
 */
public interface AlarmCurrentDao extends AlarmCurrentDaoCustom, CrudRepository<AlarmCurrent, Long> {

	@Query("from TrapOid where trapoid = ?1")
	public List<TrapOid> findByOid(String trapoid);

}

interface AlarmCurrentDaoCustom extends BaseDao<AlarmCurrent> {

	public AlarmCurrent loadAlarmCurrent(AlarmCurrent acur);

	public List<AlarmCurrent> getCurrentAlarm(final int start, final int limit);
	
	//根据ID删除当前告警
	public void deleteAcur(String aid);
}

@Component
class AlarmCurrentDaoImpl extends BaseDaoImpl<AlarmCurrent> implements
		AlarmCurrentDaoCustom {

	private EntityManagerFactory emf;

	@PersistenceUnit
	public void setEntityManagerFactory(EntityManagerFactory emf) {
		this.emf = emf;
	}

	public AlarmCurrent loadAlarmCurrent(AlarmCurrent acur) {
		EntityManager em = this.emf.createEntityManager();
		EntityTransaction trans = getEntityManager().getTransaction();
		try {
			trans.begin();
			em.persist(acur);
			trans.commit();
		} finally {
			if (em != null) {
				em.close();
			}
		}
		return acur;
	}

	@SuppressWarnings("unchecked")
	public List<AlarmCurrent> getCurrentAlarm(final int start, final int limit) {
		try {
			final String hql = "from AlarmCurrent order by id desc, sdate desc";
			javax.persistence.Query query = getEntityManager().createQuery(hql);
			query.setFirstResult(start);
			query.setMaxResults(limit);
			List<AlarmCurrent> curlist = query.getResultList();
			return curlist;
		} catch (RuntimeException re) {
			throw re;
		}
	}
	
	public void deleteAcur(String aid) {
		Session session = this.getSession();
		try {
			String sql = "delete from alarm_cur where id=?";
			SQLQuery query = session.createSQLQuery(sql);
			query.setInteger(0, Integer.parseInt(aid));
			query.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
}